package com.testingedu.action.background;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

public class PrepareParameter {
	@SuppressWarnings("unchecked")
	public static Object execute(HttpServletRequest request, Object object) {
		Map<String, String[]> parameters = request.getParameterMap();
		Set<String> names = parameters.keySet();
		List<String> fieldsList = new ArrayList<String>();
		Field[] fields = object.getClass().getDeclaredFields();
		for(int i = 0; i < fields.length; i++) {
			fieldsList.add(fields[i].getName());
		}
		for (String name : names) {
			if(!fieldsList.contains(name)) {
				continue;
			}
			try {
				Field field = object.getClass().getDeclaredField(name);
				Class clazz = field.getType();
				Constructor con = clazz.getConstructor(clazz);
				Object value = con.newInstance(parameters.get(name)[0]);
				if(name.length() == 1) {
					name = name.toUpperCase();
				} else {
					name = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
				}
				object.getClass().getDeclaredMethod("set"+name, clazz).invoke(object, value);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return object;
	}
}
